package com.zyl2015;


import java.util.ConcurrentModificationException;
import java.util.NoSuchElementException;

public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {

	@Override
	public abstract E get(int index); 

	@Override
	public boolean remove(int index) {
		 throw new UnsupportedOperationException();
	}

	@Override
	public Iterator<E> iterator() {
		return new Itr<E>();
	}
	
	
	private class Itr<E> implements Iterator<E>{
		int cursor=0;
		
		int lastRet=-1;
		
		@Override
		public E next() {
			try{
				int i=cursor;
				E next=(E) get(i);
				lastRet=i;
				cursor=i+1;
				return next;
			}catch(IndexOutOfBoundsException e){
				throw new NoSuchElementException();
			}
		}

		@Override
		public boolean hasNext() {
			return cursor!=size();
		}

		@Override
		public void remove() {
			if (lastRet < 0)
				throw new IllegalStateException();
			try {
				AbstractList.this.remove(lastRet);
				if (lastRet < cursor)
					cursor--;
				lastRet = -1;
			} catch (IndexOutOfBoundsException e) {
				throw new ConcurrentModificationException();
			}
		}

	};
	
}
